<template>
    <el-card>
<div>
    <!-- 头顶 -->
        <el-breadcrumb separator="/" class="a">
            <!-- :to="{ path: '/users' }"  跳转 -->
            <el-breadcrumb-item :to="{ path: '/users' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-form :inline="true" :model="params" class="demo-form-inline">
            <el-form-item>
                <el-button type="primary" @click="onAdd">添加角色</el-button>
            </el-form-item>     
        </el-form>
        
        <el-table class="aa"
                :data="jueseList"
                max-height="420"
                style="width: 100%">

            <el-table-column label="" width="50px" type="expand">
                <template slot-scope="scope">
                     <!-- 渲染一级 -->
                    <el-row :class="[i1==0?'':'bdtop','vcenter']"  v-for="(item,i1) in scope.row.children" :key="item.id">
                        <el-col :span="5">
                            <el-tag  closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="19">
                            <!-- 渲染二级 -->
                            <el-row :class="[i2==0?'':'bdtop','vcenter']" v-for="(obj,i2) in item.children" :key="obj.id" >
                                <el-col :span="6">
                                    <el-tag @close="removeRightById(scope.row,obj.id)" closable style="color: green;">{{obj.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <!-- 渲染三级 -->
                                    <el-tag @close="removeRightById(scope.row,obja.id)" closable 
                                    v-for="obja in obj.children" :key="obja.id" style="color: red;">{{obja.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>

            <el-table-column  label="#" type="index" />
            <el-table-column label="角色名称" prop="roleName" />
            <el-table-column label="角色描述" prop="roleDesc" />
            <el-table-column label="操作" width="280px">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary"
                        @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger"
                        @click="handleDelete(scope.row.id)">删除</el-button>
                    <el-button size="mini" type="warning" 
                        @click="handleJuese(scope.row)">分配权限</el-button>
                    </template>
            </el-table-column>

            
           

            <!-- 添加  -->
            <!-- 如果提示框不显示就在el-dialog中加：:append-to-body="true" -->
            <el-dialog
                title="添加管理员"
                :visible.sync="dialogVisible"
                width="30%" :append-to-body="true">
            <el-form ref="customform" :model="form" label-width="80px"
                    status-icon :rules="rules">
                <el-form-item label="角色名称" prop="username">
                    <el-input v-model="form.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="username">
                    <el-input v-model="form.roleDesc"></el-input>
                </el-form-item>
                
            </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="onAddUser">确 定</el-button>
                </span>
            </el-dialog>
        </el-table>
            <!-- current-page当前页
                page-size：每页记录数
                page-sizes：每页记录数下拉列表，第一个数与每页记录数必须一致
                total：总记录数 -->
                <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="params.pagenum"
                :page-sizes="[1,5, 30, 50]"
                :page-size="params.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                >
            </el-pagination>
            <!-- 编辑 -->
            <el-dialog
                :visible.sync="dialogVisibles"
                width="30%">
                <el-form ref="customform" :model="bianJI" label-width="80px"
                                        status-icon :rules="rules">
                    <el-form-item label="用户id" prop="username">
                        <el-input v-model="bianJI.id"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="username">
                        <el-input v-model="bianJI.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="username">
                        <el-input v-model="bianJI.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisibles = false">取 消</el-button>
                    <el-button type="primary" @click="onUpdUser">编 辑</el-button>
                </span>
            </el-dialog>
            <!-- 分配权限  -->
            <el-dialog
                    :visible.sync="dialogVisibless" :show-close="false"
                    width="30%">
                    <el-tree
                        ref="treeRef"
                        :model="Fenpei"
                        :data="listmenu"
                        show-checkbox
                        node-key="id"
                        @node-click="handleNodeClick"
                        default-expand-all
                        :default-checked-keys="defaultCheckedKeys"
                        :props="defaultProps">
                    </el-tree>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="quxiao">取 消</el-button>
                        <el-button type="primary" @click="onFenpei">分配</el-button>
                    </span>
            </el-dialog>
    </div>
</el-card>
</template>

<script>

export default {
   
    data(){
        return{
            jueseList:[],
            bianJI:[],
            //分配
            defaultProps: {
                children: "children",//设置子属性的名称，这个名称要与查询得到的数据结构里面的子属性名称一致
                label: "authName"//指定节点显示的名称
            },
            Fenpei:[],
            roleId:0,
            listmenu: [],
            defaultCheckedKeys:[],
            
            params:{
                roleName:'',
                roleDesc:'',
                pagenum:1,
                pagesize:5

            },
            
            form:{
                roleName:'',
                roleDesc:''
            },
            rules:{

            },
            total:0,
            dialogVisible:false,
            dialogVisibles:false,
            dialogVisibless:false,
    }},
    methods:{
        //删除某个权限
        async removeRightById(role,rightId){
            const confirmResult =await this.$confirm(
                '此操作将永久删除该权限,是否继续',
                '提示',{
                    confirmButtonText:'确定',
                    cancelButtonText:'取消',
                    type:'warning'
                }).catch(err=>err)
                
                if(confirmResult!='confirm') {
                    return this.$message.info('取消删除!')
                }
                const res =await this.$http.delete(
                    `/api/private/v1/roles/${role.id}/rights/${rightId}`
                )
                console.log('del...',res);
                if (res.meta.status!==200) {
                    return this.$message.error('删除权限失败!')
                }
                this.$message.success('删除权限成功！')
                role.children=res.data
        },
        //分配取消
        quxiao(){
            this.defaultCheckedKeys=[]
            this.dialogVisibless=false;
        },
        //分配权限
        handleNodeClick() {},
        //递归函数
        getLeafKeys(node,arr){
            if (!node.children) {
                return arr.push(node.id)
            }
            node.children.forEach(item=>(
                this.getLeafKeys(item,arr)
            ))
        },
        //点击分配
        async onFenpei(){
            let arr = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const rids = arr.join(",")
            let data=await this.$http.post(`/api/private/v1/roles/${this.roleId}/rights`,
            {rids: rids});
            if (data.meta.status!=200) {
                return this.$message.error('分配权限失败')
            }
            this.$message.success('分配权限成功')
            this.initTable();
            this.dialogVisibless=false;
            this.defaultCheckedKeys=[]
        },
        //获取分配列表
        async getlistmune(){
            let menu = await this.$http.get("/api/private/v1/rights/tree");
            console.log(menu.data);
            this.listmenu = menu.data
        },
        //点击分配权限拿值
        handleJuese(row){
            this.roleId = row.id
            //查询所有菜单并且是已经分级的格式数据
            //提供给树形组件渲染出所有的一二级菜单
            this.getlistmune()
            let data = row.children;
            this.getLeafKeys(row,this.defaultCheckedKeys)
            this.dialogVisibless=true;
        },
        //删除
        async handleDelete(_id){
            if (confirm('确定永久删除吗?')) {
                let  a= await this.$http.delete(`/api/private/v1/roles/${_id}`);
                this.initTable();
            } 
        },
        //编辑更新
        async onUpdUser(){
            let {data}=await this.$http.put(`/api/private/v1/roles/${this.bianJI.id}`,
            {"roleName":this.bianJI.roleName,"roleDesc":this.bianJI.roleDesc});
            this.initTable();
            this.dialogVisibles=false;
        },
        //编辑
        handleEdit(obj){
            this.bianJI=obj;
            this.dialogVisibles=true;
        },
        
        //添加
        async onAddUser(){
            let ret= await this.$http.post("/api/private/v1/roles",this.form)
            if (ret.meta.status!=201) {
                return this.$message.error(ret.meta.msg)
            }
            this.$message.success(ret.meta.msg)
            this.initTable();
            this.dialogVisible=false;
            // console.log(data);
        },
        //添加
        onAdd(){
            this.dialogVisible=true;
        },
        //修改每页记录数
        handleSizeChange(val){
            this.params.pagesize=val*1;
            this.initTable();
        },
        //点击分页按钮
        handleCurrentChange(val){
            this.params.pagenum=val*1;
            this.initTable();   
        },
        //列表
        async initTable(){
            let {data}=await this.$http.get("/api/private/v1/roles",
            {params:this.params});
            this.jueseList=data;
            // console.log(data);
            this.total=data.total;
        }
    },
    async mounted(){
        this.initTable();
    }
}
</script>

<style lang="scss" scoped>
        .to{
            
            display: flex;
            flex-direction: row;
            // margin-left: 20px;
        }
        .demo-form-inline{
            display: flex;
            flex-direction: row;
        }
        .a{
            width: 100%;
            height: 60px;
            background-color: #e0e5ee;
            text-align: center;
            line-height: 60px;
        }
        .el-tag{
            margin: 7px;
        }
        .bdtop{
            border-top: 1px solid #eee;;
        }
        .bdbottom{
            border-bottom: 1px solid #eee;
        }
        .vcenter{
            display: flex;
            align-items: center;
        }
</style>